//
//  CDH_RangeSensorViewController.swift
//  Transducer
//
//  Created by chendehao on 16/8/20.
//  Copyright © 2016年 CDHao. All rights reserved.
//

import UIKit

class CDH_RangeSensorViewController: UIViewController {

    @IBOutlet weak var rangeSensorLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        rangeSensorLabel.text = ""
    }
    override func viewWillAppear(animated: Bool) {
        //  打开距离传感器
        UIDevice.currentDevice().proximityMonitoringEnabled = animated
        
        // 检查有物体靠近还是离开通过通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CDH_RangeSensorViewController.proximityStateDidChange), name: UIDeviceProximityStateDidChangeNotification, object: nil)
    }
    override func viewWillDisappear(animated: Bool) {
        //  打开距离传感器
        UIDevice.currentDevice().proximityMonitoringEnabled = false
        
        // 检查有物体靠近还是离开通过通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CDH_RangeSensorViewController.proximityStateDidChange), name: UIDeviceProximityStateDidChangeNotification, object: nil)
    }
    deinit{
        // 移除通知监听者
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
extension CDH_RangeSensorViewController {
    @objc private func proximityStateDidChange() {
        if UIDevice.currentDevice().proximityState {
            rangeSensorLabel.text = "有物体靠近"
        }else {
            rangeSensorLabel.text = "物体已经离开"
        }
    }
}
